#include "user_sid34_service.h"

#include "uds_service.h"
#include "user_uds.h"

int16_t Request_Download_Port(uint8_t *rec_buf, uint8_t *rsp_buf, uint16_t rec_len)
{

    int16_t                            ret;
    req_download_req_struct           *req_dload_req;
    req_download_positive_resp_struct *req_dload_pstv_resp;

    req_dload_req = (req_download_req_struct *)rec_buf;

    req_dload_pstv_resp = (req_download_positive_resp_struct *)rsp_buf;

    // 检查请求长度
    if (rec_len != REQUEST_DOWNLOAD_MESSAGE_LEN) {

        ret = -NRC_INVALID_MESSAGE_LENGTH_OR_FORMAT;

        return ret;
    }

    // 检查数据格式标识符
    if (req_dload_req->data_format != DATA_FORMATLDENTIFIER) {

        ret = -NRC_SUBFUNCTION_NOT_SUPPORTED;

        return ret;
    }

    // 检查逻辑起始地址和长度的标识符
    if (req_dload_req->mem_add_and_size_format != MEM_ADD_AND_SIZE_FORMAT) {

        ret = -NRC_REQUEST_OUT_OF_RANGE;

        return ret;
    }

    endian_shift((uint8_t *)(&req_dload_req->mem_add), 4);

    endian_shift((uint8_t *)(&req_dload_req->mem_size), 4);

    // 检查逻辑起始地址数据
    if (req_dload_req->mem_add != UDS_APP_UPDATA_START_ADDR) {

        ret = -NRC_REQUEST_OUT_OF_RANGE;

        return ret;
    }

    // 检查文件长度数据
    if (req_dload_req->mem_size > (FLASH_ADDR_APP_CODE_MAX - FLASH_ADDR_APP_CODE)) {

        ret = -NRC_REQUEST_OUT_OF_RANGE;

        return ret;
    }

    // 准备响应数据
    req_dload_pstv_resp->positive_resp_id = USD_GET_POSITIVE_RSP(req_dload_req->sid);

    req_dload_pstv_resp->len_format = LEN_FORMAT;

    req_dload_pstv_resp->data_len_max = TRANSFER_DATA_BLOCK_LEN;

    endian_shift((uint8_t *)(&req_dload_pstv_resp->data_len_max), 2);

    // 这里不读取下发的起始地址，用户有自己的flash区规划
    // uds_status.uds_sid34_service.flash_program_addr = req_dload_req->mem_add;
    uds_status.uds_sid34_service.flash_program_addr = FLASH_ADDR_APP_CODE;

    uds_status.uds_sid34_service.flash_program_size = req_dload_req->mem_size;

    // USER_UDS_LOG("uds_status.uds_sid34_service.flash_program_size:%x\n", req_dload_req->mem_size);

    uds_status.uds_sid34_service.block_cnt_start_flag = 1;

    uds_status.uds_sid34_service.request_download_service_finish_flag = 1;

    ret = REQUEST_DOWNLOAD_RESP_LEN;

    return ret;
}